package com.gaoxin.api.contronller.selectcoursecontroller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.gaoxin.api.entity.selcourseentity.SelectCourse;
import com.gaoxin.api.service.selectcourse.SelectCourseService;
import com.gaoxin.common.exception.RRException;
import com.google.common.collect.Maps;

/**
 * 选课接口
 * 
 * @author zhaozhenshe
 * @param <E>
 *
 */
@RestController
@RequestMapping("app/selcourse")
public class SelectCourseController<E> {
	@Autowired
	private SelectCourseService selectCourseService;

	private Lock lock = new ReentrantLock();

	/**
	 * 查询当前选课起止时间段
	 * 
	 * @param paramMap
	 * @return
	 */
	@RequestMapping(value = "/queryBeginEndTime", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public String findBeginEndTime() {
		Map<String, Object> map = Maps.newHashMap();
		String jsonData = null;
		try {
			SelectCourse selectCourse = selectCourseService.findBTimeAndETime();
			if (selectCourse != null) {
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String nowDate = df.format(new Date());
				Date nowTime = df.parse(nowDate);
				Date startTime = df.parse(selectCourse.getBeginTime());
				Date endTime = df.parse(selectCourse.getEndTime());
				Boolean flag = isEffectiveDate(nowTime, startTime, endTime);
				map.put("code", "0");
				map.put("results", flag);
				jsonData = JSON.toJSONString(map);
			} else {
				map.put("code", "101002");
				map.put("errmsg", "系统内部异常，请联系管理员！");
				jsonData = JSON.toJSONString(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonData;
	}

	/**
	 * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
	 * 
	 * @param nowTime
	 *            当前时间
	 * @param startTime
	 *            开始时间
	 * @param endTime
	 *            结束时间
	 * @return
	 */
	public boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
		if (nowTime.getTime() == startTime.getTime() || nowTime.getTime() == endTime.getTime()) {
			return true;
		}
		Calendar date = Calendar.getInstance();
		date.setTime(nowTime);
		Calendar begin = Calendar.getInstance();
		begin.setTime(startTime);
		Calendar end = Calendar.getInstance();
		end.setTime(endTime);
		if (date.after(begin) && date.before(end)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据学生学号查询学生当前学年所有可选课程的信息
	 * 
	 * @param paramMap
	 * @return
	 */
	@RequestMapping(value = "/querySelCourse", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public String queryAllSeleCourseInfo(@RequestBody Map<String, String> paramMap) {
		String stuNumber = paramMap.get("stuNumber");
		Map<String, Object> map = Maps.newHashMap();
		String jsonData = null;
		try {
			SelectCourse selectCourse1 = selectCourseService.findBTimeAndETime();
			int maxCourse = selectCourse1.getMaxCourse();
			int num = selectCourseService.findStudentCourseNumber(stuNumber);
			if (num > maxCourse || num == maxCourse) {
				map.put("code", "101007");
				map.put("errmsg", "本学期您最多可以选取" + maxCourse + "门课程，已经选取了" + num + "门课程,无法继续选课！");
				jsonData = JSON.toJSONString(map);
				return jsonData;
			}
			List<SelectCourse> list = selectCourseService.findAllSelectCourse(stuNumber);// 获取所有的可选的课程信息
			List<SelectCourse> selectedList = selectCourseService.findStuSelectedCourse(stuNumber);// 获取已选课程的信息
			
			CopyOnWriteArrayList<SelectCourse>   listtem= new CopyOnWriteArrayList<SelectCourse>(list);
			CopyOnWriteArrayList<SelectCourse>   listtem2= new CopyOnWriteArrayList<SelectCourse>(selectedList);
			
			if (listtem.size() != 0 && listtem != null && listtem2.size() != 0 && listtem2 != null) {
				for (int i = 0; i < listtem.size(); i++) {
					for (int j = 0; j < listtem2.size(); j++) {
						if (listtem.get(i).getId().equals(listtem2.get(j).getId())) {
							listtem.remove(i);// 从所有的可选课程中移除已选课程
						}
					}
				}
			}
			if (listtem.size() != 0 && listtem != null) {
				// 剔除选课人数已满的课程
				for (SelectCourse selectCourse : listtem) {
					// 该门课程可选的总人数
					int totalNumber = selectCourse.getMaxNumber();
					// 统计该门课程已选人数
					int selectedNumber = selectCourseService.querySelectedNumber(selectCourse.getCourseId(),
							selectCourse.getTeacherId(), selectCourse.getClassroomId(), selectCourse.getId());
					if (totalNumber < selectedNumber || totalNumber == selectedNumber) {
						listtem.remove(selectCourse);
					}else {
						selectCourse.setSelectedNumber(selectedNumber);
						selectCourse.setIsNumber(totalNumber-selectedNumber);
					}
				}
			}
			if (listtem.size() != 0 && listtem != null) {
				map.put("code", "0");
				map.put("results", listtem);
				jsonData = JSON.toJSONString(map);
			} else {
				map.put("code", "101001");
				map.put("errmsg", "无可选课程信息！");
				jsonData = JSON.toJSONString(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonData;
	}

	/**
	 * 
	 * @param paramMap
	 * @return
	 */
	@RequestMapping(value = "/queryLikeSelCourse", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public String queryLikeSeleCourseInfo(@RequestBody Map<String, String> paramMap) {
		String stuNumber = paramMap.get("stuNumber");
		String courseName = paramMap.get("courseName");
		Map<String, Object> map = Maps.newHashMap();
		String jsonData = null;
		try {
			SelectCourse selectCourse1 = selectCourseService.findBTimeAndETime();
			int maxCourse = selectCourse1.getMaxCourse();
			int num = selectCourseService.findStudentCourseNumber(stuNumber);
			if (num > maxCourse || num == maxCourse) {
				map.put("code", "101008");
				map.put("errmsg", "本学期您最多可以选取" + maxCourse + "门课程，已经选取了" + num + "门课程,无法继续选课！");
				jsonData = JSON.toJSONString(map);
				return jsonData;
			}
			List<SelectCourse> list = selectCourseService.findLikeSelectCourse(stuNumber, courseName);// 获取所有的可以选的课程信息
			List<SelectCourse> selectedList = selectCourseService.findStuSelectedCourse(stuNumber);// 获取已选课程的信息
			
			CopyOnWriteArrayList<SelectCourse>   listtem=new CopyOnWriteArrayList<SelectCourse>(list);
			CopyOnWriteArrayList<SelectCourse>   listtem2=new CopyOnWriteArrayList<SelectCourse>(selectedList);
			if (listtem.size() != 0 && listtem != null && listtem2.size() != 0 && listtem2 != null) {
				for (int i = 0; i < listtem.size(); i++) {
					for (int j = 0; j < listtem2.size(); j++) {
						if (listtem.get(i).getId().equals(listtem2.get(j).getId())) {
							listtem.remove(i);// 从所有的可选课程中移除已选课程
						}
					}
				}
			}
			if(listtem.size() != 0 && listtem != null) {
				// 剔除选课人数已满的课程
				for (SelectCourse selectCourse : listtem) {
					// 该门课程可选的总人数
					int totalNumber = selectCourse.getMaxNumber();
					// 统计该门课程已选人数
					int selectedNumber = selectCourseService.querySelectedNumber(selectCourse.getCourseId(),
							selectCourse.getTeacherId(), selectCourse.getClassroomId(), selectCourse.getId());
					if (totalNumber < selectedNumber || totalNumber == selectedNumber) {
						listtem.remove(selectCourse);
					}else {
						selectCourse.setSelectedNumber(selectedNumber);
						selectCourse.setIsNumber(totalNumber-selectedNumber);
					}
				}
			}
			
			if (listtem.size() != 0 && listtem != null) {
				map.put("code", "0");
				map.put("results", listtem);
				jsonData = JSON.toJSONString(map);
			} else {
				map.put("code", "101001");
				map.put("errmsg", "无可选课程信息！");
				jsonData = JSON.toJSONString(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonData;
	}

	/**
	 * 根据课程id查询课程的具体选课信息
	 * 
	 * @param paramMap
	 * @return
	 */
	@RequestMapping(value = "/queryCourseInfo", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public String queryCourseInfo(@RequestBody Map<String, String> paramMap) {
		String courseId = paramMap.get("courseId");
		String teacherId = paramMap.get("teacherId");
		String classroomId = paramMap.get("classroomId");
		String id = paramMap.get("id");
		Map<String, Object> map = Maps.newHashMap();
		String jsonData = null;
		try {
			List<SelectCourse> list = selectCourseService.queryCourseInfo(courseId, teacherId, classroomId, id);
			if (list.size() != 0 && list != null) {
				map.put("code", "0");
				map.put("results", list);
				jsonData = JSON.toJSONString(map);
			} else {
				map.put("code", "101003");
				map.put("errmsg", "无法查询到该课程详细信息！");
				jsonData = JSON.toJSONString(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonData;
	}

	/**
	 * 确认选课
	 * 
	 * @param paramMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveSectionCourse", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public String verifySectionCourse(@RequestBody Map<String, String> paramMap) {
		String courseId = paramMap.get("courseId");
		String teacherId = paramMap.get("teacherId");
		String classroomId = paramMap.get("classroomId");
		String stuNumber = paramMap.get("stuNumber");
		String id = paramMap.get("id");
		Map<String, Object> map = Maps.newHashMap();
		String jsonData = null;
		try {
			SelectCourse selectCourse = selectCourseService.findBTimeAndETime();
			if (selectCourse != null) {
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String nowDate = df.format(new Date());
				Date nowTime = df.parse(nowDate);
				Date startTime = df.parse(selectCourse.getBeginTime());
				Date endTime = df.parse(selectCourse.getEndTime());
				Boolean flag = isEffectiveDate(nowTime, startTime, endTime);
				if (!flag) {
					map.put("code", "101012");
					map.put("results", "当前已不再选课时间内，无法进行选课！");
					jsonData = JSON.toJSONString(map);
					return jsonData;
				}
			} else {
				map.put("code", "101002");
				map.put("errmsg", "系统内部异常，请联系管理员！");
				jsonData = JSON.toJSONString(map);
				return jsonData;
			}
			SelectCourse selectCourse1 = selectCourseService.findBTimeAndETime();
			int maxCourse = selectCourse1.getMaxCourse();
			int num = selectCourseService.findStudentCourseNumber(stuNumber);
			if (num > maxCourse || num == maxCourse) {
				map.put("code", "1010010");
				map.put("errmsg", "您最多可以选取" + maxCourse + "门课程，已经选取了" + num + "门课程,无法继续选课！");
				jsonData = JSON.toJSONString(map);
				return jsonData;
			}
			// 该门课程可选的总人数
			int totalNumber = selectCourseService.queryTotalNumber(teacherId, courseId, classroomId, id);
			// 统计该门课程已选人数
			if (lock.tryLock(10, TimeUnit.SECONDS)) {
				try {
					int selectedNumber = selectCourseService.querySelectedNumber(courseId, teacherId, classroomId, id);
					if (totalNumber > selectedNumber) {
						int status = selectCourseService.saveStuSelctionCourse(courseId, teacherId, classroomId,
								stuNumber, id);
						if (status == 1) {
							int maxCourse1 = selectCourse1.getMaxCourse();
							int num1 = selectCourseService.findStudentCourseNumber(stuNumber);
							if(maxCourse1>num1) {
								map.put("code", "0");
								map.put("results", "选课成功！<br>已选"+num1+"门课程，还可选"+(maxCourse1-num1)+"门课程");
							}else {
								map.put("code", "0");
								map.put("results", "选课成功！<br>您最多可选"+maxCourse1+"门课程，已选"+num1+"门课程");
							}
							jsonData = JSON.toJSONString(map);
						} else {
							map.put("code", "101004");
							map.put("errmsg", "选课失败！");
							jsonData = JSON.toJSONString(map);
						}
					} else {
						map.put("code", "101005");
						map.put("errmsg", "该课程选课人数已达上限！");
						jsonData = JSON.toJSONString(map);
						return jsonData;
					}
				} catch (Exception e) {
					e.printStackTrace();
					throw e;
				} finally {
					lock.unlock();
				}
			} else {
				map.put("code", "1010011");
				map.put("errmsg", "系统正忙,请稍后在试！");
				jsonData = JSON.toJSONString(map);
				return jsonData;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RRException(e.getMessage());
		}
		return jsonData;
	}

	/**
	 * 查询已选学生已选课程信息
	 * @param paramMap
	 * @return
	 */
	@RequestMapping(value = "/querySelectedCourse", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public String findSelectedCourse(@RequestBody Map<String, String> paramMap) {
		// String courseId = paramMap.get("courseId");
		// String teacherId = paramMap.get("teacherId");
		// String classroomId = paramMap.get("classroomId");
		String stuNumber = paramMap.get("stuNumber");
		Map<String, Object> map = Maps.newHashMap();
		String jsonData = null;
		try {
			List<SelectCourse> list = selectCourseService.findStuSelectedCourse(stuNumber);
			if (list.size() != 0 && list != null) {
				map.put("code", "0");
				map.put("results", list);
				jsonData = JSON.toJSONString(map);
			} else {
				map.put("code", "101013");
				map.put("errmsg", "您还没有选取任何课程！");
				jsonData = JSON.toJSONString(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonData;
	}

	/**
	 * 删除所选选课
	 * 
	 * @param paramMap
	 * @return
	 */
	@RequestMapping(value = "/deleteCourse", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public String deleteSelectedCourse(@RequestBody Map<String, String> paramMap) {
		String courseId = paramMap.get("courseId");
		String teacherId = paramMap.get("teacherId");
		String classroomId = paramMap.get("classroomId");
		String stuNumber = paramMap.get("stuNumber");
		String id = paramMap.get("id");
		Map<String, Object> map = Maps.newHashMap();
		String jsonData = null;
		try {
			SelectCourse selectCourse = selectCourseService.findBTimeAndETime();
			if (selectCourse != null) {
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String nowDate = df.format(new Date());
				Date nowTime = df.parse(nowDate);
				Date startTime = df.parse(selectCourse.getBeginTime());
				Date endTime = df.parse(selectCourse.getEndTime());
				Boolean flag = isEffectiveDate(nowTime, startTime, endTime);
				if (!flag) {
					map.put("code", "101008");
					map.put("results", "当前已不再选课时间内，无法进行删除！");
					jsonData = JSON.toJSONString(map);
					return jsonData;
				}
			} else {
				map.put("code", "101002");
				map.put("errmsg", "系统内部异常，请联系管理员！");
				jsonData = JSON.toJSONString(map);
				return jsonData;
			}
			int status = selectCourseService.deleteStuSelctionCourse(courseId, teacherId, classroomId, stuNumber, id);
			if (status == 1) {
				map.put("code", "0");
				map.put("results", "删除成功！");
				jsonData = JSON.toJSONString(map);
			} else {
				map.put("code", "101006");
				map.put("errmsg", "删除失败！");
				jsonData = JSON.toJSONString(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonData;
	}
}
